package cn.tedu.review;

import java.util.Objects;

/*本类用于复习Object中的常用方法 复习Object中的常用方法*/
public class TestObject {
    public static void main(String[] args) {
        //4.创建小猫类的对象
        Cat c1 = new Cat();
        Cat c2 = new Cat();
        Cat c3 = new Cat("喵喵",3,99.9);
        Cat c4 = new Cat("喵喵",3,99.9);

        System.out.println(c1 == c2);//false
        System.out.println(c3 == c4);//false
        System.out.println(c1 == c4);//false
        System.out.println(c1 == c1);//true

        //6.重写equals()与hashCode()后(两个方法重写后,逻辑保持一致),比较的就是小猫对象的 类型+属性+属性值
        System.out.println(c1.equals(c2));//true
        System.out.println(c3.equals(c4));//true
        System.out.println(c1.equals(c4));//false

        //8.重写toString()后,不再打印地址值cn.tedu.review.Cat@745f
        //打印类型+属性+属性值
        System.out.println(c1);//Cat{name='null', age=0, price=0.0}
        System.out.println(c4);//Cat{name='喵喵', age=3, price=99.9}

        //9.定义字符串类型
        String s1 = "abc";
        char[] value = {'a','b','c'};
        String s2 = new String(value);
        String s3 = "aaa";
        String s4 = "abc";

        System.out.println(s1 == s2);//false
        System.out.println(s1 == s3);//false
        System.out.println(s1 == s4);//true tested //常量池中简单创建方式下,对象的内容同,对象值也相同

        System.out.println(s1);//abc
        System.out.println(s2);//abc

        System.out.println(s1.equals(s2));//true
        System.out.println(s1.equals(s3));//false
        System.out.println(s2.equals(s4));//true tested

        System.out.println(s1.hashCode());//96354  //toString是一组方法api, hashcode,euqal是一组, 互不影响
        System.out.println(s2.hashCode());//96354
        System.out.println(s3.hashCode());//96321  tested
        System.out.println(s4.hashCode());//96354
    }
}

//1.创建小猫类
class Cat{
    //2.定义属性
    String name;
    int age;
    double price;
    //3.生成无参与全参构造
    public Cat(){}
    public Cat(String name, int age, double price) {
        this.name = name;
        this.age = age;
        this.price = price;
    }
    //5.添加了重写的equals()与hashCode()
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Cat cat = (Cat) o;
        return age == cat.age && Double.compare(cat.price, price) == 0 && Objects.equals(name, cat.name);
    }
    @Override
    public int hashCode() {
        return Objects.hash(name, age, price);
    }
    //7.添加重写的toString()
    @Override
    public String toString() {
        return "Cat{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", price=" + price +
                '}';
    }
}